package com.xykj.enterprise.wechat.ext.api.identity;

import com.xykj.enterprise.wechat.bean.ext.identity.SuiteAccessToken;
import com.xykj.enterprise.wechat.ext.service.identity.IdentityService;
import com.xykj.enterprise.wechat.util.biz.BizException;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author zhouxu
 * @create 2021-04-02 16:27
 */
@Slf4j
@Function(description = "获取第三方应用凭证", parameters = {
        @Parameter(name = "suite_id", type = Type.String, description = "以ww或wx开头应用id（对应于旧的以tj开头的套件id）", required = true),
        @Parameter(name = "suite_secret", type = Type.String, description = "应用secret", required = true),
        @Parameter(name = "suite_ticket", type = Type.String, description = "企业微信后台推送的ticket", required = true),
})
@Component
public class GetSuiteAccessToken implements Action {

    @Autowired
    private IdentityService identityService;

    @Override
    public Response execute(Request request) throws Exception {
        try {
            SuiteAccessToken token = identityService.getSuiteAccessToken(
                    request.getString("suite_id"),
                    request.getString("suite_secret"),
                    request.getString("suite_ticket")
            );
            return Response.success().put("data", token);

        } catch (BizException biz) {
            log.error(biz.getErrMsg(), biz.getErrCode());
            return Response.fail(biz.getMessage(), biz.getErrCode());
        } catch (Exception e) {
            log.error("AccessToken 获取失败", e);
            return Response.fail(e);
        }
    }
}
